package com.sk.k01.m01.utils;

import com.sk.k01.m01.exception.MyException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

@ControllerAdvice
@Slf4j
public class ExceptionUtils {
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Msg error(Exception e){
        e.printStackTrace();
        return Msg.error().message("默认异常处理！");
    }

    @ExceptionHandler(ArithmeticException.class)
    @ResponseBody
    public Msg error(ArithmeticException e){
        e.printStackTrace();
        return Msg.error().message("特定异常处理！");
    }

    @ExceptionHandler(MyException.class)
    @ResponseBody
    public Msg error(MyException e){
        log.error(getMessage(e));
        e.printStackTrace();
        return Msg.error().code(e.getCode()).message(e.getMsg());
    }

    public static String getMessage(Exception e) {
        StringWriter sw = null;
        PrintWriter pw = null;
        try {
            sw = new StringWriter();
            pw = new PrintWriter(sw);
            // 将出错的栈信息输出到printWriter中
            e.printStackTrace(pw);
            pw.flush();
            sw.flush();
        } finally {
            if (sw != null) {
                try {
                    sw.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (pw != null) {
                pw.close();
            }
        }
        return sw.toString();
    }

}
